#ifndef __TDP2_HUSK_HPP__
#define __TDP2_HUSK_HPP__

#include "tdp2.hpp"

namespace TDP
{
	namespace Containers
	{
		template<class _T> class PaddedHusk
		{
			UInt8 _padByte;
			_T _instance;
		};

		template<class _T> class Husk
		{
		private:

			UInt8 _bytes[sizeof(PaddedHusk<_T>)-1];
			bool _hot;

			inline LargeUInt Padding() const
			{
				LargeUInt alignment = RDX_ALIGNOF(_T);
				const UInt8 *alignedLoc = _bytes + (alignment - 1);
				alignedLoc -= ((_bytes - reinterpret_cast<const UInt8 *>(NULL)) % alignment);
				return alignedLoc - _bytes;
			}

		public:
			inline const _T *Ptr() const
			{
				return reinterpret_cast<const _T *>(_bytes + Padding());
			}

			inline _T *Ptr()
			{
				return reinterpret_cast<_T *>(_bytes + Padding());
			}

			inline void Destroy()
			{
				if(_hot)
					Ptr()->~_T();
				_hot = false;
			}

			inline bool IsLive() const
			{
				return _hot;
			}

			inline Husk()
			{
				_hot = false;
			}
			
			inline ~Husk()
			{
				Destroy();
			}
			
			inline void operator = (const _T &rs)
			{
				Destroy();
				new (_bytes + Padding()) _T(rs);
				_hot = true;
			}

			inline _T *Liven()
			{
				_hot = true;
				return Ptr();
			}
			
			inline operator const _T * () const
			{
				return Ptr();
			}

			inline operator _T * ()
			{
				return Ptr();
			}

			inline const _T * operator -> () const
			{
				return Retype();
			}

			inline _T * operator -> ()
			{
				return Ptr();
			}
		};
	}
}

#define TDP_HNEW(pHusk, type, parameters) \
	do\
	{\
		try\
		{\
			new ((pHusk)->Liven()) type parameters;\
		}\
		catch(...)\
		{\
			(pHusk)->Destroy();\
			throw;\
		}\
	} while(0)

#endif
